package com.combetter.changxing.ui.fragment;

import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.data.BarEntry;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.combetter.changxing.R;
import com.combetter.changxing.databinding.FragmentHistoryBinding;
import com.combetter.changxing.model.EventMessage;
import com.combetter.changxing.model.History;
import com.combetter.changxing.ui.base.BaseFragment;
import com.combetter.changxing.util.Check;
import com.combetter.changxing.util.MPChartUtils;
import com.combetter.changxing.viewmodel.HistoryViewModel;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 历史Fragment
 * <p>
 * Created by 深圳唐龙飞讯科技有限公司 on 2018/6/7.
 */

public class HistoryFragment extends BaseFragment<FragmentHistoryBinding, HistoryViewModel> {
    private HistoryAdapter adapter;
    private List<String> xLabels;
    private List<BarEntry> entries;
    private List<String> titleList = new ArrayList<>();
    private Gson gson;
    private List<History.SmokeCountBean> mMainList;
    private Map<String, List<History.SmokeCountBean>> mOtherList;

    @Override
    public int setLayout() {
        EventBus.getDefault().register(this);
        return R.layout.fragment_history;
    }

    @Override
    public void init() {
        /**
         *  下拉刷新
         */
        mBinding.srlContent.setDisableContentWhenRefresh(true);
        mBinding.srlContent.setHeaderHeight(80);
        mBinding.srlContent.setRefreshHeader(new ClassicsHeader(getActivity()));
        mBinding.srlContent.setOnRefreshListener(refreshlayout -> {
            mViewModel.smokeCountMap.clear();
            mViewModel.selectHistory(mBinding.srlContent);
        });

        try {
            adapter = new HistoryAdapter(null);
            mBinding.recycler.setLayoutManager(new LinearLayoutManager(getContext()));
            mBinding.recycler.setAdapter(adapter);
        } catch (Exception e) {
            e.printStackTrace();
        }
        gson = new Gson();
        mMainList = new ArrayList<>();
        mOtherList = new HashMap<>();
    }

    @Override
    public Class createViewModel() {
        return HistoryViewModel.class;
    }

    @Override
    public void loadData() {
        mBinding.srlContent.autoRefresh();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getEventData(EventMessage message) {
        switch (message.getType()) {
            case "selectHistory":
                initData();
                break;
        }
    }

    public void initData() {
        String mainData = mViewModel.helpUtils.getMainHistory();
        if (!TextUtils.isEmpty(mainData)){
            Type listType = new TypeToken<List<History.SmokeCountBean>>() {
            }.getType();
            mMainList.clear();
            mMainList.addAll(gson.fromJson(mainData, listType));
        }
        String otherData = mViewModel.helpUtils.getOtherHistory();
        if (!TextUtils.isEmpty(otherData)) {
            Type otherListType = new TypeToken<Map<String, List<History.SmokeCountBean>>>() {
            }.getType();
            mOtherList.clear();
            mOtherList.putAll(gson.fromJson(otherData, otherListType));
        }
        xLabels = new ArrayList<>();
        entries = new ArrayList<>();


        titleList.clear();
        try {
            if (null != mMainList && mMainList.size() > 0) {
                for (int i = 0; i < mMainList.size(); i++) {
                    xLabels.add(mMainList.get(i).getClick_date());
                    entries.add(new BarEntry(i, mMainList.get(i).getCounts(), mMainList.get(i).getCounts()));
                }
                titleList.add("总数");
            }
            if (null != mOtherList && mOtherList.size() > 0) {
                for (String str : mOtherList.keySet()) {
                    if (!TextUtils.isEmpty(str)){
                        titleList.add(str);
                    }
                }
            }
            adapter.setNewData(titleList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 历史记录adapter
     */
    class HistoryAdapter extends BaseQuickAdapter<String, BaseViewHolder> {

        public HistoryAdapter(@Nullable List<String> data) {
            super(R.layout.fragment_history_item, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, String item) {
            try {
                BarChart chart = helper.getView(R.id.chart);
                TextView tvTitle = helper.getView(R.id.tv_title);
                if (Check.isEmpty(item)) {
                    MPChartUtils.NotShowNoDataText(chart);
                    return;
                }
                if (item.equals("总数")) {
                    tvTitle.setText(item);
                    tvTitle.setBackgroundColor(getResources().getColor(R.color.title_green));
                    // 1.配置基础图表配置
                    MPChartUtils.configBarChart(chart, xLabels, getResources().getColor(R.color.title_green));
                    //  2,初始化数据并绘制
//                    getDealEntries(entries);
                    MPChartUtils.initBarChart(chart, entries, item, getResources().getColor(R.color.title_green), xLabels.size());
                } else {
                    tvTitle.setText(item);
                    tvTitle.setBackgroundColor(getResources().getColor(R.color.colorBar));
                    if (!Check.isEmpty(mOtherList)) {
                        for (String str : mOtherList.keySet()) {
                            if (item.equals(str)) {
                                xLabels = new ArrayList<>();
                                entries = new ArrayList<>();
                                for (int i = 0; i < mOtherList.get(str).size(); i++) {
                                    xLabels.add(mOtherList.get(str).get(i).getClick_date());
                                    entries.add(new BarEntry(i, mOtherList.get(str).get(i).getCounts()));
                                }
                                // 1.配置基础图表配置
                                MPChartUtils.configBarChart(chart, xLabels, getResources().getColor(R.color.colorBar));
                                //  2,初始化数据并绘制
                                MPChartUtils.initBarChart(chart, entries, item, getResources().getColor(R.color.colorBar), xLabels.size());
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


}
